package com.jugheadzhou.auth.core.websocket.manager;

import com.jugheadzhou.auth.core.websocket.WebSocketConnection;
import com.jugheadzhou.auth.core.websocket.WebSocketManager;
import com.jugheadzhou.auth.core.websocket.utils.WebSocketUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单机部署WebSocket管理类
 *
 * @author jugheadzhou
 */
public class MemWebSocketManager implements WebSocketManager {
    /**
     * websocket的session不能被序列化，所以只能保存在内存中，不能存在redis中。
     * 通过redis的发布订阅功能实现集群部署情况下的websocket能够被正确消费
     */
    private final Map<String, WebSocketConnection> connections = new ConcurrentHashMap<>(100);

    @Override
    public WebSocketConnection get(String connectionId) {
        return connections.get(connectionId);
    }

    @Override
    public void put(String connectionId, WebSocketConnection webSocketConnection) {
        connections.put(connectionId, webSocketConnection);
    }

    @Override
    public void remove(String connectionId) {
        connections.remove(connectionId);
    }

    @Override
    public Map<String, WebSocketConnection> localWebSocketMap() {
        return connections;
    }

    @Override
    public void sendMessage(String connectionId, String message) {
        WebSocketConnection webSocketConnection = get(connectionId);
        if (webSocketConnection != null) {
            WebSocketUtil.sendMessage(webSocketConnection.getSession(), message);
        }
    }

    /**
     * 发送消息
     *
     * @param connectionId 标识
     * @param message      消息
     */
    @Override
    public void sendMessageAsync(String connectionId, String message) {
        WebSocketConnection webSocketConnection = get(connectionId);
        if (webSocketConnection != null) {
            WebSocketUtil.sendMessageAsync(webSocketConnection.getSession(), message);
        }
    }

    @Override
    public void broadcast(String message) {
        localWebSocketMap().values().forEach(
                webSocketConnection -> WebSocketUtil.sendMessageAsync(webSocketConnection.getSession(), message)
        );
    }

    @Override
    public void onMessage(String connectionId, String message) {

    }
}
